import axios from 'axios';

// 后端 API 基础 URL
const API_BASE_URL = 'http://localhost:8080/api';

// 创建 axios 实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器：添加 JWT token
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('jwt_token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器：处理错误
apiClient.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response?.status === 401) {
      // Token 过期或无效，清除本地数据
      localStorage.removeItem('jwt_token');
      localStorage.removeItem('user_info');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

class ApiService {
  // ==================== 认证相关 ====================
  
  /**
   * 用户注册
   * @param {Object} userData - 注册信息
   * @param {string} userData.username - 用户名
   * @param {string} userData.password - 密码
   * @param {string} userData.email - 邮箱
   * @param {string} userData.phone - 手机号
   * @param {string} userData.nickname - 昵称
   * @param {string} userData.walletAddress - 钱包地址
   */
  async register(userData) {
    try {
      console.log('🌐 API: 发送注册请求...', userData);
      const response = await apiClient.post('/auth/register', userData);
      console.log('🌐 API: 注册响应:', response.data);
      
      // 统一返回格式
      const isSuccess = response.data.code === 200 || response.data.success === true;
      return {
        success: isSuccess,
        message: response.data.message,
        data: response.data.data
      };
    } catch (error) {
      console.error('🌐 API: 注册请求失败:', error);
      throw this.handleError(error);
    }
  }

  /**
   * 用户登录
   * @param {string} username - 用户名
   * @param {string} password - 密码
   */
  async login(username, password) {
    try {
      console.log('🌐 API: 发送登录请求...', {username});
      const response = await apiClient.post('/auth/login', {
        username,
        password,
      });
      
      console.log('🌐 API: 登录原始响应:', response);
      console.log('🌐 API: 登录响应数据:', response.data);
      
      // 适配后端响应格式：{code: 200, message: '...', data: {...}}
      const isSuccess = response.data.code === 200 || response.data.success === true;
      
      if (isSuccess && response.data.data) {
        // 保存 token 和用户信息
        const { token, user } = response.data.data;
        console.log('🌐 API: 提取的 token:', token);
        console.log('🌐 API: 提取的 user:', user);
        
        localStorage.setItem('jwt_token', token);
        localStorage.setItem('user_info', JSON.stringify(user));
        
        console.log('✅ localStorage 已保存');
      }
      
      // 统一返回格式为 {success: boolean, data: {...}}
      return {
        success: isSuccess,
        message: response.data.message,
        data: response.data.data
      };
    } catch (error) {
      console.error('🌐 API: 登录请求失败:', error);
      throw this.handleError(error);
    }
  }

  /**
   * 退出登录
   */
  logout() {
    localStorage.removeItem('jwt_token');
    localStorage.removeItem('user_info');
  }

  /**
   * 获取当前用户信息
   */
  getCurrentUser() {
    const userInfo = localStorage.getItem('user_info');
    return userInfo ? JSON.parse(userInfo) : null;
  }

  /**
   * 检查是否已登录
   */
  isAuthenticated() {
    return !!localStorage.getItem('jwt_token');
  }

  // ==================== 用户管理相关 ====================

  /**
   * 根据 ID 获取用户信息
   * @param {number} userId - 用户 ID
   */
  async getUserById(userId) {
    try {
      const response = await apiClient.get(`/users/${userId}`);
      const isSuccess = response.data.code === 200 || response.data.success === true;
      return {
        success: isSuccess,
        message: response.data.message,
        data: response.data.data
      };
    } catch (error) {
      throw this.handleError(error);
    }
  }

  /**
   * 根据用户名获取用户信息
   * @param {string} username - 用户名
   */
  async getUserByUsername(username) {
    try {
      const response = await apiClient.get(`/users/username/${username}`);
      return response.data;
    } catch (error) {
      throw this.handleError(error);
    }
  }

  /**
   * 更新用户信息
   * @param {number} userId - 用户 ID
   * @param {Object} userData - 要更新的用户数据
   */
  async updateUser(userId, userData) {
    try {
      const response = await apiClient.put(`/users/${userId}`, userData);
      const isSuccess = response.data.code === 200 || response.data.success === true;
      
      // 如果更新的是当前用户，更新本地存储
      const currentUser = this.getCurrentUser();
      if (currentUser && currentUser.id === userId && isSuccess) {
        localStorage.setItem('user_info', JSON.stringify(response.data.data));
      }
      
      return {
        success: isSuccess,
        message: response.data.message,
        data: response.data.data
      };
    } catch (error) {
      throw this.handleError(error);
    }
  }

  /**
   * 测试后端连接
   */
  async testConnection() {
    try {
      const response = await apiClient.get('/auth/test');
      return response.data;
    } catch (error) {
      throw this.handleError(error);
    }
  }

  // ==================== 错误处理 ====================

  handleError(error) {
    if (error.response) {
      // 服务器返回错误
      const message = error.response.data?.message || error.response.data?.error || '请求失败';
      return new Error(message);
    } else if (error.request) {
      // 请求发出但没有收到响应
      return new Error('无法连接到服务器，请检查后端是否运行');
    } else {
      // 其他错误
      return new Error(error.message || '未知错误');
    }
  }
}

export default new ApiService();

